<template>
  <div class="insp">
    <div class="insp-header">
      <div class="flexBetween">
        <div class="flex insp-header-left">
          <el-input placeholder="请输入巡检模板名称" clearable v-model="tmplName" size="small" style="width: 180px;" class="mRight10"
            clearable>
          </el-input>
          <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" style="width:200px;"
            v-model="tmplTime" type="datetime" size="small" placeholder="请选择模板创建时间" class="mRight10" clearable>
          </el-date-picker>
          <el-button type="primary" size="small" @click="queryForPage(1)">
            查询
          </el-button>
        </div>
        <div class="insp-header-right">
          <el-button size="small" class="insp-btn-add" icon="el-icon-plus" @click="handleAdd">新增模板</el-button>
        </div>
      </div>
    </div>

    <div class="insp-content">
      <div class="insp-table">
        <el-table :data="tableData" stripe :header-cell-style="{
          background: '#8595B9',
          color: '#fff',
          height: '44px',
        }" max-height="660px">
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table :data="props.row.itemList" :header-cell-style="{
                color: '#999',
                height: '44px',
              }" style="width: 100%; border: 1px solid #EBEEF5; border-bottom:0" class="insp-table-expand">
                <el-table-column label="桥梁名称" prop="ownName" show-overflow-tooltip></el-table-column>
                <el-table-column label="巡检项名称" prop="name" show-overflow-tooltip></el-table-column>
                <el-table-column label="巡检规范" property="inspStandard" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span> {{ inspStandardText(scope.row.inspStandard) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="巡检人员" property="itemUserList" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span> {{ inspPersonText(scope.row.itemUserList) }}</span>
                  </template>
                </el-table-column>

              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="tmplName" label="模板名称" show-overflow-tooltip></el-table-column>
          <el-table-column property="inspType" label="巡检类型" width="100">
            <template slot-scope="scope">
              <label :class="['insp-table-label', inspTypeClass(scope.row.inspType)]">
                {{ inspTypeText(scope.row.inspType) }}
              </label>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
          <el-table-column prop="creater" label="创建人" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-tooltip content="修改">
                <el-button type="text" icon="el-icon-edit-outline" @click="handelEdit(scope.row.id)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除">
                <el-button type="text" icon="el-icon-delete" style="color: red !important;"
                  @click="handelDelete(scope.row.id)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="新增任务">
                <el-button type="text" icon="el-icon-circle-plus-outline" @click="handleAddTask(scope.row.id)">
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="insp-page">
        <el-pagination background layout="prev, pager, next" :current-page.sync="currentPage"
          :hide-on-single-page="false" @current-change="handlePageChange" :page-size="pageSize" :total="recordsTotal">
        </el-pagination>
      </div>
    </div>

    <!--新增/编辑模板-->
    <vx-popup :title="dialogTitle" width="1000px" @close="cancelSubmit" :active.sync="dialogVisible"
      @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
        <div class="insp-task-addPage-basic">
          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="模板名称 :" prop="name" label-width="95px">
                <el-input v-model="ruleForm.name" placeholder="请输入模板名称" size="small" style="width:100%" clearable>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="巡检类型 :" prop="inspType" label-width="95px">
                <el-select v-model="ruleForm.inspType" placeholder="请选择巡检类型" size="small" style="width:100%" clearable>
                  <el-option label="日常巡检" :value="0"></el-option>
                  <el-option label="定期巡检" :value="1"></el-option>
                  <!-- <el-option label="特殊巡检" :value="2"></el-option> -->
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="insp-task-addPage-line" v-for="(item,index) in ruleForm.inspBridges" :key="index"
          style="height:118px;">
          <div class="insp-task-addPage-left">
            <div class="insp-task-addPage-item">
              <el-form-item label="巡检桥梁 :" :prop="'inspBridges[' + index + '].bridge'"
                :rules="{required: true, message: '请选择巡检桥梁', trigger: 'change'}" label-width="95px">
                <el-select v-model="item.bridge" placeholder="请选择巡检桥梁" size="small" style="width:300px"
                  @change="(event)=>handleBridgeChange(event,index)" clearable value-key="id">
                  <el-option v-for="temp in bridgeOptions" :key="temp.id" :label="temp.name" :value="temp">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="insp-task-addPage-item">
              <el-form-item label="巡检项 :" :prop="'inspBridges[' + index + '].name'"
                :rules="{required: false, message: '请选择巡检项', trigger: 'change'}" label-width="95px">
                <el-cascader v-model="item.name" :options="deasePosOptions[index]||[]"
                  @change="(event)=>handleChangeDeasePos(event,index)" :key="isResouceShow"
                  :props="{label:'name',value:'value',children:'children'}" size="small" style="width:300px"
                  placeholder="请选择巡检项" clearable>
                </el-cascader>
              </el-form-item>
            </div>
            <div class="insp-task-addPage-item">
              <el-form-item label="巡检规范 :" :prop="'inspBridges[' + index + '].inspStandard'"
                :rules="{required: true, message: '请选择巡检规范', trigger: 'change'}" label-width="95px">
                <el-select v-model="item.inspStandard" placeholder="请选择巡检规范" size="small" style="width:300px" clearable>
                  <el-option label="城市桥梁" :value="0"></el-option>
                  <el-option label="道路桥梁" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="insp-task-addPage-item">
              <el-form-item label="巡检员 :" :prop="'inspBridges[' + index + '].itemUserList'"
                :rules="{required: true, message: '请选择巡检员', trigger: 'change'}" label-width="95px">
                <el-select v-model="item.itemUserList" placeholder="请选择巡检员" size="small" multiple collapse-tags
                  style="width:300px" clearable>
                  <el-option v-for="item in personOptions" :key="item.realId" :label="item.name"
                    :value="`${item.realId};${item.name}`">
                  </el-option>
                  <div style="text-align:center">
                    <el-pagination @current-change="handlePageChange_sel" :current-page.sync="currentPage_sel"
                      :page-size="pagesize_sel" layout="prev, pager, next" :total="recordsTotal_sel">
                    </el-pagination>
                  </div>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="insp-task-addPage-right">
            <div class="insp-task-addPage-item">
              <el-form-item lable-width="0">
                <el-button circle size="mini" type="danger" style="margin-left:10px" icon="el-icon-minus"
                  @click="handleDeleteItem(item,index)">
                </el-button>
              </el-form-item>
            </div>
          </div>
        </div>

        <div class="insp-task-addPage-btn">
          <el-button size="mini" type="primary" class="insp-task-addBtn" icon="el-icon-plus" @click="handleAddLine">
          </el-button>
        </div>

      </el-form>
    </vx-popup>

    <!--新增模板任务-->
    <AddInspTask ref="addInspTaskChild" :createType='1' @closeAddInspTask="()=>{}"></AddInspTask>


  </div>
</template>
<script>
  import AddInspTask from "./components/addInspTask";
  export default {
    data() {
      return {
        isResouceShow: 0,
        pageSize: 14,
        currentPage: 1,
        recordsTotal: 0,
        tmplName: '',
        tmplTime: '',
        tableData: [],
        dialogTitle: '新增模板',
        dialogVisible: false,
        editId: '',
        bridgeOptions: [],
        personOptions: [],
        deasePosOptions: {},
        ruleForm: {
          name: '',
          inspType: '',
          inspBridges: [{
            bridge: '',
            name: [],
            inspStandard: '',
            itemUserList: []
          }]
        },
        rules: {
          name: [{
            required: true,
            message: "请输入模板名称",
            trigger: "blur"
          }],
          inspType: [{
            required: true,
            message: "请选择巡检类型",
            trigger: "change"
          }]
        },
        currentPage_sel: 1,
        pagesize_sel: 10,
        recordsTotal_sel: 0
      };
    },
    components: {
      AddInspTask
    },
    created() {
      this.queryBridgeList();
      this.queryPersonList(1);
      this.queryForPage(1);
    },
    methods: {
      emptyForm() {
        this.$refs["ruleForm"].resetFields();
        const emptyObj = {
          name: '',
          inspType: '',
          inspBridges: [{
            bridge: '',
            name: [],
            inspStandard: '',
            itemUserList: []
          }]
        }
        this.ruleForm = emptyObj;
      },
      handleAdd() {
        this.emptyForm();
        this.editId = null;
        this.dialogTitle = '新增模板';
        this.dialogVisible = true;
      },
      handleAddTask(val) {
        this.$refs.addInspTaskChild.add(val);
      },
      handelDelete(val) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.insp.deleteTmpl(val).then(response => {
            if (response.data.success) {
              this.$vs.notify({
                text: '删除成功',
                color: "success",
                icon: "success"
              })
              let maxPage = Math.ceil((this.recordsTotal - 1) / this.pageSize);
              if (this.currentPage > maxPage) {
                this.currentPage = maxPage
              }
              this.handlePageChange(this.currentPage);
            } else {
              this.$vs.notify({
                text: "删除失败",
                color: "danger"
              })
            }
          })
        }).catch(() => {
          this.$vs.notify({
            text: "已取消删除",
            color: "primary"
          })
        });
      },
      handelEdit(val) {
        this.$refs["ruleForm"].resetFields();
        this.dialogTitle = '编辑模板';
        this.dialogVisible = true;
        this.editId = val;
        this.queryTmplById(val);
      },
      queryForPage(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage = 1;
        }
        const _params = {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
          data: {
            name: this.tmplName,
            dt: this.tmplTime || ''
          }
        }
        this.$api.insp.queryTmplPage(_params).then(response => {
          if (response.data.success) {
            this.tableData = response.data.data.map((item, index) => {
              return {
                id: item.id,
                tmplName: item.name,
                inspType: item.inspType,
                createTime: item.dt,
                creater: item.createUserName,
                itemList: item.itemList
              }
            });
            this.recordsTotal = response.data.recordsTotal;
          }
        });
      },
      queryBridgeList() {
        this.$api.bridge.AllTheBridges().then(response => {
          if (response.data.success) {
            this.bridgeOptions = response.data.data[0];
          }
        });
      },
      queryTmplById(val) {
        this.$api.insp.queryTmplById(val).then(response => {
          const _data = response.data.data;
          let _inspBridges = _data.itemList.map((item, index) => {
            let _itemUserList = item.itemUserList.map(userItem => `${userItem.userId};${userItem.userName}`);
            let _ext1 = JSON.parse(item.ext1);
            this.handleBridgeChange(_ext1, index);
            return {
              name: [`${item.constructionId};${item.constructionName}`,
                `${item.partsId};${item.partsName}`
              ],
              inspStandard: item.inspStandard,
              bridge: _ext1,
              itemUserList: _itemUserList
            }
          });
          let _ruleForm = {
            name: _data.name,
            inspType: _data.inspType,
            inspBridges: _inspBridges
          }
          this.ruleForm = _ruleForm;
        });
      },
      handleAddLine() {
        this.ruleForm.inspBridges.push({
          bridge: '',
          name: [],
          inspStandard: '',
          itemUserList: []
        });
      },
      handleDeleteItem(item, index) {
        this.ruleForm.inspBridges.splice(index, 1);
      },
      handleSubmit() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          let _userInfo = JSON.parse(localStorage.getItem("userInfo"));
          let _itemList = this.ruleForm.inspBridges.map(item => {
            let _itemUserList = item.itemUserList.map(temp => ({
              userId: temp.split(';')[0],
              userName: temp.split(';')[1],
            }));
            let _ext1 = {
              // ...item.bridge,
              id: item.bridge['id'] || '',
              name: item.bridge['name'] || '',
              lng: item.bridge['lng'] || '',
              lat: item.bridge['lat'] || '',
              bridgeTypeId: item.bridge['bridgeTypeId'] || '',
              bridgeTypeName: item.bridge['bridgeTypeName'] || '',
              province: item.bridge['provinceName'] || '',
              city: item.bridge['municipalityName'] || '',
              area: item.bridge['regionName'] || '',
              standardName: item.bridge['standardName'] || '',
            };
            return {
              name: item.name.length > 0 ? `${item.name[0].split(';')[1]}/${item.name[1].split(';')[1]}` : '',
              constructionId: item.name.length > 0 ? item.name[0].split(';')[0] : '',
              constructionName: item.name.length > 0 ? item.name[0].split(';')[1] : '',
              partsId: item.name.length > 0 ? item.name[1].split(';')[0] : '',
              partsName: item.name.length > 0 ? item.name[1].split(';')[1] : '',
              ownId: item.bridge['id'] || '',
              ownName: item.bridge['name'] || '',
              inspTmplCfgPos: {
                ownId: item.bridge['id'] || '',
                ownName: item.bridge['name'] || '',
                lon: item.bridge['lng'] || '',
                lat: item.bridge['lat'] || '',
              },
              inspStandard: item.inspStandard,
              itemUserList: _itemUserList,
              ext1: JSON.stringify(_ext1)
            }
          });
          let _params = {
            createUserId: _userInfo['userid'] || '',
            createUserName: _userInfo['realname'] || '',
            name: this.ruleForm.name,
            inspType: this.ruleForm.inspType,
            itemList: _itemList
          };
          if (this.editId) {
            _params.id = this.editId;
          }

          if (this.editId) {
            this.$api.insp.updateTmpl(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '修改成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.queryForPage(1);
              }
            });
          } else {
            this.$api.insp.addTmpl(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '新增成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.queryForPage(1);
              }
            });
          }
        });
      },
      queryPersonList(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage_sel = 1;
        }
        const _params = {
          pageSize: this.pagesize_sel,
          pageNum: this.currentPage_sel,
          type: '0' //巡检人员类型
        }
        this.$api.personManager.getPersonList(_params).then(response => {
          if (response.data.success) {
            this.personOptions = response.data.data;
            this.recordsTotal_sel = response.data.recordsTotal;
          }
        });
      },
      handlePageChange_sel(currentPage) {
        this.currentPage_sel = currentPage;
        this.queryPersonList();
      },
      handlePageChange(currentPage) {
        this.currentPage = currentPage;
        this.queryForPage();
      },
      cancelSubmit() {
        this.dialogVisible = false;
      },
      handleBridgeChange(event, index) {
        const _params = {
          bridgeTypeId: event['bridgeTypeId'] || '',
          pId: '-1',
          bridgeId: event['id'] || ''
        };
        this.queryConstructionModelTreeById(_params, index);
      },
      handleChangeDeasePos(event, index) {
        console.log(this.ruleForm.inspBridges[index].name);
      },
      deepDeasePosOptions(data) {
        let _arr = [];
        let _obj = {};
        data.forEach(item => {
          const _tmp = {
            ...item
          };
          if (_tmp.children && _tmp.children.length > 0) {
            _tmp.children = this.deepDeasePosOptions(_tmp.children);
          }
          _obj = {
            id: _tmp.id,
            name: _tmp.name,
            value: `${_tmp.id};${_tmp.name}`,
          }
          if (_tmp.children && _tmp.children.length > 0) {
            _obj.children = _tmp.children;
          }
          _arr.push(_obj);
        });
        return _arr;
      },
      queryConstructionModelTreeById(_params, index) {
        this.$api.bridge.queryConstructionModelTreeById(_params).then(response => {
          if (response.data.success) {
            ++this.isResouceShow;
            this.deasePosOptions[index] = this.deepDeasePosOptions(response.data.data.children);
          }
        });
      },
      inspPersonText(list) {
        let _text = '';
        list.forEach((item, index) => {
          if (!index) {
            _text += item.userName
          } else {
            _text += `、${item.userName}`
          }
        });
        return _text;
      },
      inspStandardText(type) {
        switch (type) {
          case 0:
            return '城市桥梁';
          case 1:
            return '道路桥梁';
        }
      },
      inspTypeClass(type) {
        switch (type) {
          case 0:
            return 'inspTypeA';
          case 1:
            return 'inspTypeB';
          case 2:
            return 'inspTypeC';
        }
      },
      inspTypeText(type) {
        switch (type) {
          case 0:
            return '日常巡检';
          case 1:
            return '定期巡检';
          case 2:
            return '特殊巡检';
        }
      },

    },
  };

</script>
<style scoped lang="scss">
  @import './insp.scss';

  /deep/.el-table__header tr,
  /deep/.el-table__header th {
    padding: 0;
    height: 44px;
  }

  /deep/.el-table td,
  /deep/.el-table th {
    text-align: center;
    font-size: 14px;
  }

  /deep/.el-table th {
    font-weight: 500;
    color: #fff;
  }

  /deep/.el-table td {
    font-weight: 400;
    color: #444;
    padding: 0;
    height: 44px;
    line-height: 44px;
  }

  /deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
    background: #F1F5FC;
  }

  /deep/.el-table__expanded-cell {
    padding: 20px !important;
  }

  /deep/.el-button--mini.insp-task-addBtn {
    padding: 6px;
    font-size: 18px;
    font-weight: bolder;
  }

</style>
